package main

import (
	"fmt"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/infrastructure/common/utils"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/infrastructure/startup"
	"git.myscrm.cn/golang/common/ykenv"
	stark "git.myscrm.cn/golang/stark/v4"
	"git.myscrm.cn/golang/stark/v4/app"
	"git.myscrm.cn/golang/stark/v4/config/setting"
	"github.com/gin-gonic/gin"
	"log"
	"time"
)

// 此处定义当前服务的名字
const APP_NAME = "micro-gfyx-bigdata-service"
const GIN_APP_NAME = "gin" + "-" + APP_NAME

func main() {
	if ykenv.IsDevMode() {
		utils.TestTool()
	}

	runner, err := app.NewRunner(&stark.Application{
		Name:       APP_NAME,
		Type:       stark.APP_TYPE_GRPC,
		LoadConfig: startup.LoadConfig,
		SetupVars:  startup.SetupVars,
	})
	if err != nil {
		log.Fatalf("app.NewRunner err: %v", err)
	}

	// 启动gin 服务
	RunHttpServer(runner)

	err = runner.ListenGRPCServer(&stark.GRPCApplication{
		RegisterGRPCServer:      startup.RegisterGRPCServer,
		RegisterGateway:         startup.RegisterGateway,
		RegisterHttpRoute:       nil,
		UnaryServerInterceptors: startup.RegisterMiddleware(),
	})

	if err != nil {
		log.Fatalf("runer.ListenGRPCServer err: %v", err)
	}
}

func RunHttpServer(runner *app.Runner) {
	go func() {
		for i := 0; i <= 100; i++ {
			// 延迟三秒等待grpc服务启动完
			time.Sleep(time.Second * 3)
			// 判断启动grpc服务成功, 虽然这样判断不是很准确，但是也基本没问题
			if setting.ServerSetting.EndPoint != "" {
				//fmt.Println("启动grpc服务成功")
				// 启动http gin 服务
				// etcd服务注册，获取端口号，避免和grpc的端口重名，利用runner注册，注册后回滚appname
				runner.App.Name = GIN_APP_NAME
				serviceInfo, err := runner.ServiceRegister()
				runner.App.Name = APP_NAME
				if err != nil {
					panic("gin服务ServiceRegister失败:" + err.Error())
					return
				}

				addr := "0.0.0.0:" + serviceInfo.ServicePort
				r := gin.Default()

				err = startup.RegisterHttpRoute(r)
				if err != nil {
					panic("gin RegisterHttpRoute error: " + err.Error())
					return
				}
				fmt.Println("gin server start addr: ", addr)
				err = r.Run(addr)
				if err != nil {
					panic("gin server start error: " + err.Error())
				}
				break
			} else {
				fmt.Println("等待grpc启动完毕...")
			}
		}
	}()
}
